package test.top2.com.atguigu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import test.top2.com.atguigu.bean.TableProcess;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: JdbcUtil
 * Package: test.top2.com.atguigu.utils
 * Description:
               select * from t;                                 多行多列
 *             select count(*) from t;                          单行单列
 *             select count(*) from t group by dept_name;       单行多列
 *             select * from t where id = 'xxx'; id为主键        多行单列
 * @Author ChenJun(有志男青年)
 * @Create 2023/4/27 19:40
 * @Version 1.0
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreToCamel) throws Exception {

        // 创建集合用于存放结果
        ArrayList<T> list = new ArrayList<>();

        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 遍历resultSet,将每行数据封装为T对象
        while (resultSet.next()){

            //创建t对象
            T t = clz.newInstance();

            for (int i = 1; i < columnCount + 1; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                //大小写  驼峰转换
                if (underScoreToCamel){
                    columnName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName.toLowerCase());
                }

                //封装t对象
                BeanUtils.setProperty(t,columnName,value);

            }
            list.add(t);
        }

        //返回集合
        return list;
    }

    public static void main(String[] args) throws Exception {

//        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();
        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/gmall_config?" + "user=root&password=000000&useUnicode=true&" + "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");

        List<TableProcess> jsonObjects = JdbcUtil.queryList(connection,
                "select * from table_process where sink_type ='dim' ",
                TableProcess.class, true);

        for (TableProcess jsonObject : jsonObjects) {
            System.out.println(jsonObject);
        }

        //关闭连接
        connection.close();
    }
}
